<?php
/**
 * Created by PhpStorm.
 * User: sunzexin
 * Date: 2018/2/25
 * Time: 14:50
 */

namespace App\Http\Logics\MiniProgram;

use App\Dynamic;
use App\DynamicPhoto;
use App\DynamicVideo;
use App\UserPraiseDynamic;
use Illuminate\Support\Facades\Redis;
use App\Http\Logics\BaseLogic;
use App\Http\Logics\CommonLogic;
class DynamicLogic extends BaseLogic
{
    /**
     * 发布图片动态
     * @param $data
     * @return mixed
     */
    public static function createPhotoDynamic($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code){
            return self::response($response->code);
        }
        $user_id = $response->data;
        $dynamic = new Dynamic();
        $dynamic->type = Dynamic::PHOTO;
        $dynamic->user_id = $user_id;
        $dynamic->latlng = $data['latlng'];
        $dynamic->address = $data['address'];
        $dynamic->address_name = $data['address_name'];
        $response = self::getAddr($data['latlng']);
        if ($response->code){
            return self::response($response->code);
        }
        $address_component = $response->data;
        $dynamic->citycode = $address_component->citycode;
        $dynamic->adcode = $address_component->adcode;
        $dynamic->content = $data['content'];
        if (!$dynamic->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }

        // 保存咖啡馆图片
        $photo_list_arr = json_decode($data['photo_list_str']);
        foreach ($photo_list_arr as $item){
            $url = $item->url."?imageInfo";
            // 处理图片
            $rs = dealHttp($url);
            $width = $rs->width;
            $height = $rs->height;
            $dynamic_photo = new DynamicPhoto();
            $dynamic_photo->dynamic_id = $dynamic->id;
            $dynamic_photo->url = $item->url;
            $dynamic_photo->sort = $item->sort;
            $dynamic_photo->width = $width;
            $dynamic_photo->height = $height;
            if (!$dynamic_photo->save()){
                return self::response(self::OBJECT_SAVE_FAIL);
            }
        }

        return self::response(self::SUCCESS);
    }

    /**
     * 创建视频动态
     * @param $data
     * @return mixed
     */
    public static function createVideoDynamic($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code){
            return self::response($response->code);
        }
        $user_id = $response->data;
        $dynamic = new Dynamic();
        $dynamic->type = Dynamic::VIDEO;
        $dynamic->user_id = $user_id;
        $dynamic->latlng = $data['latlng'];
        $dynamic->address = $data['address'];
        $dynamic->address_name = $data['address_name'];
        $response = self::getAddr($data['latlng']);
        if ($response->code){
            return self::response($response->code);
        }
        $address_component = $response->data;
        $dynamic->citycode = $address_component->citycode;
        $dynamic->adcode = $address_component->adcode;
        $dynamic->content = $data['content'];
        if (!$dynamic->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }

        $dynamic_video = new DynamicVideo();
        $dynamic_video->dynamic_id = $dynamic->id;
        $dynamic_video->url = $data['video_url'];
        $dynamic_video->cover = $data['video_url'].'.0_0.p0.jpg';

        // 判断视频是否转码
        $data_two = [
            'key' => $dynamic_video->cover,
            'value' => 'dynamic_video'
        ];
        if (!CommonLogic::cacheVideoInfo($data_two)){
            $dynamic_video->height = Redis::get($dynamic_video->cover.'-height');
            $dynamic_video->width = Redis::get($dynamic_video->cover.'-width');
            $dynamic_video->is_transcode = DynamicVideo::TRANSCODE;
            Redis::del($dynamic_video->cover.'-height');
            Redis::del($dynamic_video->cover.'-widht');
        }

        if (!$dynamic_video->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }

        return self::response(self::SUCCESS);
    }

    /**
     * 获取动态列表
     * @param $data
     * @return mixed
     */
    public static function getDynamicList($data)
    {
        $query = Dynamic::with(['dynamicVideo', 'dynamicPhoto', 'user', 'city', 'praisedUser'])->withCount(['dynamicComment', 'userPraiseDynamic'])->whereHas('dynamicVideo', function($query) use ($data){
            if (isset($data['is_transcode']) && $data['is_transcode'] != ''){
                $query->where('is_transcode', $data['is_transcode']);
            }
        })->orWhereHas('dynamicPhoto', function ($query){
            $query->where('id', '>', 0);
        })->where(function ($query) use ($data) {
            if (isset($data['status']) && !empty($data['status'])){
                $query->where('status', $data['status']);
            }
        })->orderBy('created_at', 'desc');
        $dynamic = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
        if (empty($dynamic)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        foreach ($dynamic as $dy) {
            $photo = $dy->dynamicPhoto()->get();
            $photo = $photo->take(6);
            foreach ($photo as $item) {
                if (empty($item->width)) {
                    $item->width = 1;
                    $item->height = 1;
                }
                $item->ratio = $item->width / $item->height;

                if ($item->count() == 6)
                    $item->ratio = 1;
            }
            layout($photo);

            // 获取每个咖啡馆的图片
            $dy->dynamic_photo_part = $photo;
        }

        // 判断是否分页
        $dynamic_second = $data['limit'] ? $dynamic->items() : $dynamic;

        // 如果登录，则加上用户对每个咖啡馆的关注状态
        if (!empty($data['loginSession'])){
            $response = self::checkUserPraiseDynamic($data['loginSession'], $dynamic_second);
            if ($response->code){
                return self::response($response->code);
            }
        }
        return self::response(self::SUCCESS, $dynamic);
    }

    /**
     * 判断用户是否关注咖啡馆
     * @param $loginSession 用户的验证秘钥
     * @param $cafe_second 咖啡馆列表
     * @return mixed
     */
    public static function checkUserPraiseDynamic($loginSession, $dynamic_second)
    {
        $response = self::getUserIdByLoginSession($loginSession);
        if ($response->code) {
            return self::response($response->code);
        }
        $user_id = $response->data;

        if (count($dynamic_second) > 1 || gettype($dynamic_second) === 'array'){
            foreach ($dynamic_second as $item) {
                // 判断咖啡馆的关注者是否为空，如果为空则直接判断该用户没有关注该咖啡馆
                if (empty($item->praisedUser)){
                    $item->is_praise = UserPraiseDynamic::NOT_PRAISE;
                }else{
                    // 判断用户是否在关注者列表中
                    $followed_user_id_arr = array_column($item->praisedUser->toArray(), 'id');
                    $item->is_praise = in_array($user_id, $followed_user_id_arr) ? UserPraiseDynamic::HAS_PRAISE : UserPraiseDynamic::NOT_PRAISE;
                }
            }
        }else{
            // 判断咖啡馆的关注者是否为空，如果为空则直接判断该用户没有关注该咖啡馆
            if (empty($dynamic_second->praisedUser)){
                $dynamic_second->is_praise = UserPraiseDynamic::NOT_PRAISE;
            }else{
                $response = self::getUserIdByLoginSession($loginSession);
                if ($response->code) {
                    return self::response($response->code);
                }
                $user_id = $response->data;

                // 判断用户是否在关注者列表中
                $followed_user_id_arr = array_column($dynamic_second->praisedUser->toArray(), 'id');

                $dynamic_second->is_praise = in_array($user_id, $followed_user_id_arr) ? UserPraiseDynamic::HAS_PRAISE : UserPraiseDynamic::NOT_PRAISE;
            }
        }
        return self::response(self::SUCCESS);
    }

    /**
     * 获取动态详情
     * @param $data
     * @return mixed
     */
    public static function getDynamicDetail($data)
    {
        $dynamic = Dynamic::with(['user', 'dynamicVideo', 'dynamicPhoto'])->withCount(['dynamicComment', 'userPraiseDynamic'])->find($data['dynamic_id']);
        if (empty($dynamic)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        // 如果登录，则加上用户对每个咖啡馆的关注状态
        if (!empty($data['loginSession'])){
            $response = self::checkUserPraiseDynamic($data['loginSession'], $dynamic);
            if ($response->code){
                return self::response($response->code);
            }
        }
        return self::response(self::SUCCESS, $dynamic);
    }
}